<?php

class MakedepositController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex() {
        //output the accout list
        outputJsByList(Coa::model()->getListWithDesc(), 'accountList');
        $depno=getIncrementNumber('tbl_rec_led', 'depno')+1;
        
        $this->render('index',array(
            'depno'=>$depno
        ));
    }

    public function actionSaveDeposit() {
        if (isset($_POST['list']) && isset($_POST['data'])) {
            $data = $_POST['list'];

            $total = 0;

            $account = $_POST['data']['account'];
            
            $date = date('Y-m-d');
            $memo = $_POST['data']['memo'];
            
            if ($account == NULL || $date == NULL || $memo == NULL) {
                echo json_encode(array(
                    'success' => false,
                    'msg' => 'Missing data make deposit'
                ));
                return;
            }
            if (!is_array($data) || count($data) <= 0 || count($data) > 18) {
                echo json_encode(array(
                    'success' => false,
                    'msg' => 'Must select payment(s) to make deposit'
                ));

                return;
            }
         
            try {
                $transid = getIncrementNumber('tbl_rec_led', 'fintransid') + 1;
                $depno=getIncrementNumber('tbl_rec_led', 'depno')+1;
                foreach ($data as $item) {

                    $recled = RecLed::model()->findByPk($item);
                    /* @var $recled RecLed */
                    $recled->depositdate = $date;
                    $recled->depno = $depno;
                    $recled->fintransid = $transid;
                    $recled->depositFlag = 1;
                    $total+=$recled->amount;
                    if ($recled->save() == false) {
                        echo json_encode($recled->getErrors());
                        return;
                    }
                }
                $transnum = getIncrementNumber('tbl_fin_ledger', 'trannumber') + 1;
                $fin1 = new FinLedger;
               
                $fin1->amount = -$total; //negative amount
                $fin1->accountid = '1099';
                $fin1->docnum = $depno;
                $fin1->transid = $transid;
                $fin1->source = 800;
                $fin1->transtype = 805;
                $fin1->transmemo = $memo;
                $fin1->trancount = 1;
                $fin1->transdesc = "Deposit {$depno}";
                $fin1->transdate = date('Y-m-d');
                $fin1->trannumber = $transnum;

                $fin2 = new FinLedger;
              
                $fin2->amount = $total; //positive
                $fin2->accountid = $account;
                $fin2->docnum = $depno;
                $fin2->transid = $transid;
                $fin2->source = 800;
                $fin2->transtype = 805;
                $fin2->transmemo = $memo;
                $fin2->trancount = 2; //trancount increment by 1
                $fin2->transdesc = "Deposit {$depno}";
                $fin2->transdate = date('Y-m-d');
                $fin2->trannumber = $transnum;

                if ($fin1->save() == FALSE) {
                    echo json_encode($fin1->getErrors());
                }
                if ($fin2->save() == FALSE) {
                    echo json_encode($fin2->getErrors());
                }
              

                echo json_encode(array(
                    'success' => true,
                    'msg' => 'Save successful'
                ));
            } catch (Exception $e) {
                echo json_encode(array(
                    'success' => false,
                    'msg' => $e->getMessage()
                ));
             
                return;
            }
        }
    }

    public function actionList($query=NULL, $page=0, $sort=NULL, $dir=NULL) {
        if ($page > 0)
            $page--;
        $order = CJSON::decode($sort);

        $crit = new CDbCriteria();
        $crit->addCondition('depositdate is NULL');

        $crit->order = isset($order) ? $order[0]['property'] . ' ' . $order[0]['direction'] : NULL;
        $data = new CActiveDataProvider('RecLed', array(
                    'criteria' => $crit,
                    'pagination' => array(
                        'pageSize' => 9999999999999,
                        'currentPage' => $page
                    )
                ));
        
        if ($data != NULL && count($data->getData()) > 0) {
            $rs = array();
            $rs['totalCount'] = $data->getTotalItemCount();
            foreach ($data->getData() as $i => $item) {
                /* var Warehouse $item */
                $rs['data'][$i] = $item->getAttributes();
                if($item->customer!=null){
                    $rs['data'][$i]['customer'] = $item->customer->lastname;
                }
                $rs['data'][$i]['paymethodtext'] = PaymentMethods::getDesc($item->paymethod);
                
            }
            echo json_encode($rs);
        }
     
        Yii::app()->end();
    }

    public function actionPrintTicket() {
        $this->layout = '//layouts/space';

        Yii::import('application.extensions.MPDF53.*');
        require_once('mpdf.php');
    
        if (isset($_POST['recledlist']) && isset($_POST['deposit'])) {
            $data = $_POST['recledlist'];

            $total = 0;

            $account = $_POST['deposit']['account'];
            $depno = $_POST['deposit']['deposit'];
            $date = $_POST['deposit']['date'];
            $memo = $_POST['deposit']['memo'];
            //$print=$_POST['deposit']['printticket'];
            if ($account == NULL || $depno == NULL || $date == NULL || $memo == NULL) {
                echo json_encode(array(
                    'success' => false,
                    'msg' => 'Missing data make deposit'
                ));
                return;
            }
            if (!is_array($data) || count($data) <= 0 || count($data) > 18) {
                echo json_encode(array(
                    'success' => false,
                    'msg' => 'Must select payment(s) to make deposit'
                ));

                return;
            }
            $modelArray = array();

            foreach ($data as $i => $item) {
                $model = RecLed::model()->findByPk($item);
                if ($model == NULL) {
                    echo json_encode(array(
                        'success' => false,
                        'msg' => 'Can not load data'
                    ));
                    return;
                }
                $total+=$model->amount;
                $modelArray[] = $model;
            }

            $html = $this->render('printticket', array(
                'depno' => $depno,
                'date' => $date,
                'memo' => $memo,
                'total' => $total,
                'data' => $modelArray
                    ), true);
            //echo $html;
            $pdf = new mPDF('-s');

            $pdf->SetDisplayMode('fullpage');
            $pdf->WriteHTML($html);
            $pdf->Output();
            exit;
        }else{
            echo json_encode(array(
            'success'=>false,
            'msg'=>'Please support data to process'
        ));
        }
        
    }

}

